#!/usr/bin/env python
#
# author windcao@hotmail.com
# Setup script for PIL 1.1.5 and later
#
# Usage: python png_optimizer.py -f"icon.png" -c"genConf"
#
# -*- coding: utf-8 -*-
import os

import sys
import getopt
from file_utils import *


def usage():
    print 'Gen images for small file size:'
    print '    python png_optimizer.py -z"images/"'


def version():
    print 'png_optimizer.py 1.0.0.0'


def optimize_one_image(src_image_file, output_dir, output_file):
    if not os.path.isfile(src_image_file):
        print u"param miniImageFile('{0:s}') is not file".format(output_file)
        return

    if not os.path.isdir(output_dir):
        os.makedirs(output_dir)

    print "genMiniImage to :'%s'" % (os.path.join(output_dir, output_file))
    os.system("./pngquant/pngquant --quality=80-85 {0:s} --skip-if-larger -f --output {1:s}".format(src_image_file,
                                                                                                    os.path.join(
                                                                                                        output_dir,
                                                                                                        output_file)))


def optimize_images_under_dir(src_image_dir):
    if not os.path.isdir(src_image_dir):
        print u'{0:s} is not dir'.format(src_image_dir)
        return

    for parent, dirs, file_names in os.walk(src_image_dir):
        for filename in file_names:
            file2optimize = os.path.join(parent, filename)
            output_dir = parent + "_mini_out"
            optimize_one_image(file2optimize, output_dir, filename)


def optimize_images_by_project_config(project_config):
    lines = read_lines(project_config)

    for line in lines:
        if line.startswith('#'):
            continue
        find_file_to_optimize(line, '')


def find_file_to_optimize(icon_dir, output_dir_tag):
    # list_dirs = os.walk(icon_dir)
    files_to_optimize = []

    for parent, dirs, file_names in os.walk(icon_dir):
        for filename in file_names:
            file2optimize = os.path.join(parent, filename)
            output_dir = parent + output_dir_tag
            if filename.endswith('.png') and not filename.endswith(".9.png"):
                files_to_optimize.append([file2optimize, output_dir, filename])

    for file2optimize, output_dir, filename in files_to_optimize:
        print u"file:{0:s}\n,output_dir:{1:s}\n,filename:{2:s}\n".format(file2optimize, output_dir, filename)
        optimize_one_image(file2optimize, output_dir, filename)


def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], 'hvi:p:', ['image_tobe_optimized=', 'projectConfig='])
    except getopt.GetoptError, err:
        print str(err)
        usage()
        sys.exit(2)
    project_config_file = ''
    image_tobe_optimized = ''
    for o, a in opts:
        if o in ('-h', '--help'):
            usage()
            sys.exit(1)
        elif o in ('-v', '--version'):
            version()
            sys.exit(0)
        elif o in ('-p', '--projectConfig'):
            project_config_file = a
            break
        elif o in ('-i', '--image_tobe_optimized'):
            image_tobe_optimized = a
            break
        else:
            usage()
            sys.exit(3)

    if len(project_config_file) > 0:
        print "processing projects....."
        optimize_images_by_project_config(project_config_file)
    elif len(image_tobe_optimized) > 0:
        print u"images to mini = {0:s}".format(image_tobe_optimized)
        optimize_images_under_dir(image_tobe_optimized)
    else:
        usage()
        sys.exit(2)


if __name__ == '__main__':
    main(sys.argv)